<div class="layuimini-container">
    <div class="layui-form-item">
        <label class="layui-form-label">规格名</label>
        <div class="layui-input-block" id='specs-id'>
            {volist name="specs" id="vo"}
                <input type="checkbox" lay-filter="specs"  class="specs{$vo.id}" name="specs[]" data-title="{$vo.title}" title="{$vo.title}" value="{$vo.id}" content="{$vo.content}" data-id="{$vo.id}" data-key="{:count($specs)}" {in name="$vo.id" value="$row.specs"}checked{/in}>
               
            {/volist}
        </div>
    </div>
    <form action="" class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">规格：</label>
            <div class="layui-input-block">
                <table class="layui-table" id="spec-table">
                    <thead>
                        <tr>
                            <th>规格名</th>
                            <th>规格值</th>
                        </tr>
                    </thead>
                    <tbody data-specs-value="{$row.specs_value}" data-skus="{$row.skus}" id="specs-value">
                       
                    </tbody>
                </table>
            </div>
        </div>
 
        <div class="layui-form-item layui-hide">
            <label class="layui-form-label">SKU表：</label>
            <div class="layui-input-block">
                <table class="layui-table" id="sku-table">
                    <thead></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </form>
</div>
<script>

        
layui.use(['form', 'upload', 'jquery'], function() {
    var form = layui.form,
        upload = layui.upload,
        $ = layui.jquery;

    var skus =  $('#specs-value').attr('data-skus')
 
       
    if (skus) {
        skus = JSON.parse(skus)
      
    }
    console.log(skus)
    function createSkuTable(url = '/admin/ajax/upload') {
        var specData = [];
        $.each($('#spec-table tbody tr'), function() {
            var child = [];
            $.each($(this).find('input[type=checkbox]'), function() {
                child.push({ id: $(this).val(), title: $(this).attr('title'), checked: $(this).is(':checked') });
            });
            var specItem = { id: $(this).find('td').eq(0).attr('data-id'), title: $(this).find('td').eq(0).text(), show: $(this).find('input[type=checkbox]:checked').length > 0, child: child };
            specData.push(specItem);
        });

        if ($('#spec-table tbody input[type=checkbox]:checked').length) {
            $('#sku-table').parent().parent().removeClass('layui-hide');
        
            var prependThead = [],
                prependTbody = [];
            $.each(specData, function() {
                if (this.show) {
                    prependThead.push(this.title);
                    var prependTbodyItem = [];
                    $.each(this.child, function() {
                        if (this.checked) {
                            prependTbodyItem.push({ id: this.id, title: this.title });
                        }
                    });
                    prependTbody.push(prependTbodyItem);
                }
            });
            if (prependThead.length > 0) {
                $('#sku-table thead').html('<tr>' +
                    prependThead.map(function(t, i, a) {
                        return '<th>' + t + '</th>'
                    }) +
                    '<th>图片</th>' +
                    '<th>原价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                    '<th>活动价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                    '<th>库存 <i class="layui-icon layui-icon-cols"></i></th>' +
                    '</tr>');
                 
            }

            var prependTbodyTrs = [];
            var prependTbodyTrsPrice = [];
            prependTbody.reduce(function(prev, cur, index, array) {
                var tmp = [];
                prev.forEach(function(a) {
                    cur.forEach(function(b) {
                        tmp.push({ id: a.id + ',' + b.id, title: a.title + ',' + b.title });
                    })
                });
                return tmp;
            }).forEach(function(item, index, array) {
                let aa=item.id
                console.log(item.id)
                // console.log(skus[aa])
                // return false;
                if(skus[item.id]!=undefined){

                
                if (!skus[item.id]['picture']) {
                   skus[item.id]['picture'] = '__STATIC__/admin/images/sku-add.png'
                }
                // console.log(skus['凌风系列,平铺尾箱垫,卡宴黄,拉维丝,5座,到店安装']['price'])
                // return;
                // if (skus[item.id]['status'] == 1) {
                //     var normal  = 'selected'
                //     var no  = ''
                // }else{
                //     var normal = ''
                //     var no = 'selected'
                // }
                var  attrCate="";
                var  attrCateMember="";
                var  attrCateActivity="";
                     attrCate+='<input type="text" name="skus[' + item.id + '][price]" id="price'+index+'" value="'+skus[item.id]['price']+'" class="layui-input" lay-verify="required|number" lay-reqtext="原价不能为空">' 
                    attrCateActivity+='<input type="text" name="skus[' + item.id + '][activity_price]" id="activity_price'+index+'" value="'+skus[item.id]['activity_price']+'" class="layui-input" lay-verify="required|number" lay-reqtext="活动价不能为空">'
                prependTbodyTrs.push('<tr>' +
                    item.title.split(',').map(function(t, i, a) {
                        return '<td>' + t + '</td>';
                    }) +
                    '<td><input type="hidden" name="skus[' + item.id + '][picture]" value="'+skus[item.id]['picture']+'"><img src="'+skus[item.id]['picture']+'" alt="sku图片"></td>' +
                    '<td>'+attrCate+'</td>' +
                    '<td>'+attrCateActivity+'</td>' +
                    '<td><input type="text" name="skus[' + item.id + '][stock]" value="'+skus[item.id]['stock']+'" id="stock'+index+'" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                    '</tr>');
                }
            });
            attrCate="";
            attrCateMember="";
            attrCateActivity="";
        
            if (prependTbodyTrs.length > 0) {
                $('#sku-table tbody').html(prependTbodyTrs.join(''));
                $('input[name=spec]').val(JSON.stringify(specData));
                form.render();
                upload.render({
                    elem: '#sku-table td img',
                    url: url,
                    exts: 'png|jpg|ico|jpeg|gif',
                    accept: 'images',
                    acceptMime: 'image/*',
                    multiple: false,
                    done: function(res) {
                        if (res.code === 1) {
                            var url = res.data.url;
                            // console.log(url)
                            $(this.item).attr('src', url).prev().val(url);
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                        return false;
                    }
                });
                upload.render({
                    elem: '#sku-price td img',
                    url: url,
                    exts: 'png|jpg|ico|jpeg|gif',
                    accept: 'images',
                    acceptMime: 'image/*',
                    multiple: false,
                    done: function(res) {
                        if (res.code === 1) {
                            var url = res.data.url;
                            // console.log(this.item)
                            $(this.item).attr('src', url).prev().val(url);
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                        return false;
                    }
                });
            }
        } else {
            $('#sku-table').parent().parent().addClass('layui-hide');
            $('#sku-table thead').html('');
            $('#sku-table tbody').html('');
            $('input[name=spec]').val('');
        }
    }

    /**
     * 初始化sku表
     */
    createSkuTable();

    /**
     * 监听sku表变化
     */
    form.on('checkbox(filter)', function(data) {
        createSkuTable();
    });

     /**
     * 监听批量赋值
     */
     $(document).on('click', '#sku-table thead tr th i', function() {
        var that = this;
        layer.prompt(function(value, index, elem) {
            $.each($('#sku-table tbody tr'), function() {
                $(this).find('td').eq($(that).parent().index()).children('input').val(value);
            });
            layer.close(index);
        });
    });

    /**
     * 监听表单提交
     */
    form.on('submit(submit)', function(data) {
        var state = Object.keys(data.field).some(function(item, index, array) {
            return item.startsWith('skus');
        });
        state ? layer.alert(JSON.stringify(data.field), { title: '提交的数据' }) : layer.msg('sku表数据不能为空', { icon: 5, anim: 6 });
        return false;
    });

    // 选择规格模板
    form.on('checkbox(specs)', function(data) {

        let dataId = $(this).attr('data-id')

        let hasId = $('#spec-table tbody').find('tr').hasClass('specs'+dataId)
        // console.log(hasId)
        if (hasId) {
            $('.specs'+dataId).remove()
            return false
        }
        let content = $(this).attr('content')

        let contentArr = content.split(',')

        let = input = ''
        for(var i in contentArr){
            input += '<input type="checkbox" title="'+contentArr[i]+'" lay-filter="filter" value="'+contentArr[i]+'">'
        }
        $('#spec-table tbody').append('<tr class="specs'+dataId+'"><td>'+data.value+'</td><td>'+input+'</td></tr>')
        form.render()
        createSkuTable()
    });

    var specsValue =  $('#specs-value').attr('data-specs-value')
    if (specsValue) {
        var specsValue = JSON.parse(specsValue)
    }
    // 初始化
    $('#specs-id').find('input').each(function(o){
        let dataId = $(this).attr('data-id')
        let title = $(this).attr('data-title')
        let key = $(this).attr('data-key')

        // console.log(11111111,key)

        let content = $(this).attr('content')

        let contentArr = content.split(',')

        let = input = ''
        for(var i in contentArr){
            for (var k in specsValue) {
              // console.log(k)
              // console.log(specsValue[k])
              if (title == k) {
                // console.log(1, specsValue[k])
                // console.log(specsValue[k].indexOf(contentArr[i]))
                if(specsValue[k].indexOf(contentArr[i]) >= 0){
                    var isChecked = 'checked'
                    
                }else{
                    var isChecked = ''
                }
              }
            }
            input += '<input type="checkbox" title="'+contentArr[i]+'" lay-filter="filter" '+isChecked+' name="specs_value['+title+'][]" value="'+contentArr[i]+'">'
        }
        $('#spec-table tbody').append('<tr class="specs'+dataId+'"><td>'+title+'</td><td>'+input+'</td></tr>')
        form.render()
        if (o == key-1) {
            createSkuTable()
        }
        
    })

});
/*
批量赋值
*/
function batchadd(){
    var that=this;
    var picture=''
    var stock=0
    var price=[]
    var member_price=[]
    var activity_price=[]
    var price_show=0
    var member_show=0
    var activity_show=0
    //取值
    $.each($('#sku-price tbody tr').find("td"), function(index, value) {
 
                 switch (index) {
                    case 1:
                        price.push($(this).find('input').val())
                        break;
                    case 2:
                        activity_price.push($(this).find('input').val())
                    break; 
                        case 0:
                        picture=$(this).children('input').val()
                    break;
                    case 3:
                        stock=$(this).children('input').val()
                    break; 
                   
                }
                
    });
    
   //赋值
   $.each($('#sku-table tbody tr'), function(index, value) {
       var _this=this;
            $.each($(this).children('td'),function(i,v){
            
                if($(this).find('img').length>0){
                    if(picture){
                        $(this).find("input[type=hidden]").val(picture)
                        $(this).find('img').attr('src',picture)
                    } 
                }
                if($(this).find('#stock'+index).val()){
                    $(this).find('#stock'+index).val(stock)
                }
                if($(this).find('#price'+index)){
                    $(this).find('#price'+index).val(price[0])
                }

               
            });
           form.render('checkbox')
             
   });
   
}
</script>